<template>
  <div class="main">
    <!-- 搜索表单 -->
    <el-card class="filter-card">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="报名编号">
          <el-input
            v-model="filterForm.enrollmentNo"
            placeholder="请输入报名编号"
            clearable
            class="!w-[150px]"
          />
        </el-form-item>
        <el-form-item label="学员姓名">
          <el-input
            v-model="filterForm.studentName"
            placeholder="请输入学员姓名"
            clearable
            class="!w-[120px]"
          />
        </el-form-item>
        <el-form-item label="培训课程">
          <el-select
            v-model="filterForm.trainingId"
            placeholder="请选择培训课程"
            clearable
            class="!w-[180px]"
          >
            <el-option
              v-for="training in trainingOptions"
              :key="training.id"
              :label="training.title"
              :value="training.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="报名状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择状态"
            clearable
            class="!w-[120px]"
          >
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="报名时间">
          <el-date-picker
            v-model="filterForm.enrollDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="!w-[240px]"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline :icon="Search" />
            查询
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline :icon="Refresh" />
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline :icon="Download" />
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="mb-4">
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total-icon">
              <IconifyIconOffline :icon="FileText" />
            </div>
            <div class="stat-info">
              <div class="stat-title">总报名数</div>
              <div class="stat-value">{{ enrollmentStats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon pending-icon">
              <IconifyIconOffline :icon="Clock" />
            </div>
            <div class="stat-info">
              <div class="stat-title">待审核</div>
              <div class="stat-value">{{ enrollmentStats.pending }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon approved-icon">
              <IconifyIconOffline :icon="Check" />
            </div>
            <div class="stat-info">
              <div class="stat-title">已通过</div>
              <div class="stat-value">{{ enrollmentStats.approved }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon rate-icon">
              <IconifyIconOffline :icon="TrendingUp" />
            </div>
            <div class="stat-info">
              <div class="stat-title">通过率</div>
              <div class="stat-value">{{ enrollmentStats.approvalRate }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 报名列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>报名列表</span>
          <div>
            <el-button type="warning" @click="handleBatchApprove" :disabled="!selectedRows.length">
              <IconifyIconOffline :icon="Check" />
              批量通过
            </el-button>
            <el-button type="danger" @click="handleBatchReject" :disabled="!selectedRows.length">
              <IconifyIconOffline :icon="Close" />
              批量拒绝
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="enrollmentList" 
        style="width: 100%" 
        stripe 
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="enrollmentNo" label="报名编号" width="140" />
        <el-table-column prop="studentName" label="学员姓名" width="100" />
        <el-table-column prop="studentPhone" label="手机号码" width="130" />
        <el-table-column prop="trainingTitle" label="培训课程" min-width="150" show-overflow-tooltip />
        <el-table-column prop="trainingPrice" label="课程费用" width="100" align="center">
          <template #default="{ row }">
            <span class="text-red-600 font-bold">¥{{ row.trainingPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="报名状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="paymentStatus" label="支付状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getPaymentTagType(row.paymentStatus)" size="small">
              {{ getPaymentText(row.paymentStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="enrollDate" label="报名时间" width="110">
          <template #default="{ row }">
            {{ formatDate(row.enrollDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="approveDate" label="审核时间" width="110">
          <template #default="{ row }">
            {{ row.approveDate ? formatDate(row.approveDate) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="approver" label="审核人" width="100">
          <template #default="{ row }">
            {{ row.approver || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleView(row)">
              <IconifyIconOffline :icon="View" />
              查看
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              link 
              type="success" 
              size="small" 
              @click="handleApprove(row)"
            >
              <IconifyIconOffline :icon="Check" />
              通过
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              link 
              type="danger" 
              size="small" 
              @click="handleReject(row)"
            >
              <IconifyIconOffline :icon="Close" />
              拒绝
            </el-button>
            <el-button 
              v-if="row.status === 'approved' && row.paymentStatus === 'unpaid'"
              link 
              type="warning" 
              size="small" 
              @click="handlePaymentReminder(row)"
            >
              <IconifyIconOffline :icon="Bell" />
              催缴
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 报名详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="报名详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="currentEnrollment" class="enrollment-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="报名编号">{{ currentEnrollment.enrollmentNo }}</el-descriptions-item>
          <el-descriptions-item label="学员姓名">{{ currentEnrollment.studentName }}</el-descriptions-item>
          <el-descriptions-item label="手机号码">{{ currentEnrollment.studentPhone }}</el-descriptions-item>
          <el-descriptions-item label="邮箱地址">{{ currentEnrollment.studentEmail }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ currentEnrollment.studentIdCard }}</el-descriptions-item>
          <el-descriptions-item label="培训课程">{{ currentEnrollment.trainingTitle }}</el-descriptions-item>
          <el-descriptions-item label="课程费用">
            <span class="text-red-600 font-bold">¥{{ currentEnrollment.trainingPrice }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="报名状态">
            <el-tag :type="getStatusTagType(currentEnrollment.status)" size="small">
              {{ getStatusText(currentEnrollment.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="支付状态">
            <el-tag :type="getPaymentTagType(currentEnrollment.paymentStatus)" size="small">
              {{ getPaymentText(currentEnrollment.paymentStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="报名时间">{{ formatDate(currentEnrollment.enrollDate) }}</el-descriptions-item>
          <el-descriptions-item label="审核时间">{{ currentEnrollment.approveDate ? formatDate(currentEnrollment.approveDate) : '-' }}</el-descriptions-item>
          <el-descriptions-item label="审核人">{{ currentEnrollment.approver || '-' }}</el-descriptions-item>
          <el-descriptions-item label="报名备注" :span="2">{{ currentEnrollment.remark || '-' }}</el-descriptions-item>
          <el-descriptions-item label="拒绝原因" :span="2" v-if="currentEnrollment.rejectReason">
            <span class="text-red-600">{{ currentEnrollment.rejectReason }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 操作记录 -->
        <div class="mt-4">
          <h4>操作记录</h4>
          <el-timeline>
            <el-timeline-item
              v-for="record in currentEnrollment.operationRecords"
              :key="record.id"
              :timestamp="formatDateTime(record.createTime)"
              :type="getTimelineType(record.type)"
            >
              <div>
                <div class="font-bold">{{ record.title }}</div>
                <div class="text-gray-600">{{ record.content }}</div>
                <div class="text-sm text-gray-400">操作人：{{ record.operator }}</div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button 
          v-if="currentEnrollment?.status === 'pending'"
          type="success" 
          @click="handleApprove(currentEnrollment)"
        >
          通过审核
        </el-button>
        <el-button 
          v-if="currentEnrollment?.status === 'pending'"
          type="danger" 
          @click="handleReject(currentEnrollment)"
        >
          拒绝审核
        </el-button>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog
      v-model="approveDialogVisible"
      :title="approveType === 'approve' ? '通过审核' : '拒绝审核'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form ref="approveFormRef" :model="approveForm" :rules="approveRules" label-width="80px">
        <el-form-item v-if="approveType === 'reject'" label="拒绝原因" prop="rejectReason">
          <el-input
            v-model="approveForm.rejectReason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因"
          />
        </el-form-item>
        <el-form-item label="审核备注" prop="remark">
          <el-input
            v-model="approveForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入审核备注（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="approveDialogVisible = false">取消</el-button>
        <el-button 
          :type="approveType === 'approve' ? 'success' : 'danger'" 
          @click="handleApproveSubmit" 
          :loading="approveLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import FileText from "@iconify-icons/ep/document";
import Clock from "@iconify-icons/ep/clock";
import Check from "@iconify-icons/ep/check";
import Close from "@iconify-icons/ep/close";
import TrendingUp from "@iconify-icons/ep/trend-charts";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";
import Download from "@iconify-icons/ep/download";
import View from "@iconify-icons/ep/view";
import Bell from "@iconify-icons/ep/bell";
import dayjs from "dayjs";

defineOptions({
  name: "TrainingEnrollment"
});

// 筛选表单
const filterForm = ref({
  enrollmentNo: "",
  studentName: "",
  trainingId: "",
  status: "",
  enrollDateRange: []
});

// 报名统计
const enrollmentStats = ref({
  total: 234,
  pending: 45,
  approved: 156,
  approvalRate: 85.2
});

// 培训课程选项
const trainingOptions = ref([
  { id: 1, title: "羽毛球基础培训" },
  { id: 2, title: "乒乓球进阶课程" },
  { id: 3, title: "网球专业训练" },
  { id: 4, title: "篮球技巧提升" },
  { id: 5, title: "游泳入门教学" }
]);

// 报名列表
const enrollmentList = ref([]);
const loading = ref(false);
const selectedRows = ref([]);

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 弹窗控制
const detailDialogVisible = ref(false);
const approveDialogVisible = ref(false);
const approveLoading = ref(false);
const approveType = ref("approve"); // approve | reject

// 当前报名信息
const currentEnrollment = ref(null);

// 审核表单
const approveForm = ref({
  rejectReason: "",
  remark: ""
});

// 表单引用
const approveFormRef = ref();

// 审核表单验证规则
const approveRules = {
  rejectReason: [{ required: true, message: "请输入拒绝原因", trigger: "blur" }]
};

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap = {
    pending: "warning",
    approved: "success",
    rejected: "danger",
    cancelled: "info"
  };
  return statusMap[status] || "info";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap = {
    pending: "待审核",
    approved: "已通过",
    rejected: "已拒绝",
    cancelled: "已取消"
  };
  return statusMap[status] || status;
};

// 获取支付状态标签类型
const getPaymentTagType = (status: string) => {
  const statusMap = {
    unpaid: "danger",
    paid: "success",
    refunded: "warning"
  };
  return statusMap[status] || "info";
};

// 获取支付状态文本
const getPaymentText = (status: string) => {
  const statusMap = {
    unpaid: "未支付",
    paid: "已支付",
    refunded: "已退款"
  };
  return statusMap[status] || status;
};

// 获取时间线类型
const getTimelineType = (type: string) => {
  const typeMap = {
    enroll: "primary",
    approve: "success",
    reject: "danger",
    payment: "warning",
    cancel: "info"
  };
  return typeMap[type] || "primary";
};

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD");
};

// 格式化日期时间
const formatDateTime = (date: string) => {
  return dayjs(date).format("YYYY-MM-DD HH:mm");
};

// 生成模拟数据
const generateMockData = () => {
  const mockData = [];
  const names = ["张三", "李四", "王五", "赵六", "钱七", "孙八", "周九", "吴十"];
  const statuses = ["pending", "approved", "rejected", "cancelled"];
  const paymentStatuses = ["unpaid", "paid", "refunded"];
  
  for (let i = 1; i <= 80; i++) {
    const status = statuses[Math.floor(Math.random() * statuses.length)];
    const paymentStatus = status === "approved" ? 
      paymentStatuses[Math.floor(Math.random() * 2)] : "unpaid";
    const trainingId = Math.floor(Math.random() * 5) + 1;
    const training = trainingOptions.value.find(t => t.id === trainingId);
    const enrollDate = dayjs().subtract(Math.floor(Math.random() * 90), 'day');
    
    mockData.push({
      id: i,
      enrollmentNo: `EN${dayjs().format('YYYYMMDD')}${String(i).padStart(4, '0')}`,
      studentName: names[Math.floor(Math.random() * names.length)] + i,
      studentPhone: `138${String(Math.floor(Math.random() * 100000000)).padStart(8, '0')}`,
      studentEmail: `student${i}@example.com`,
      studentIdCard: `${Math.floor(Math.random() * 900000) + 100000}${Math.floor(Math.random() * 90) + 10}${Math.floor(Math.random() * 9000) + 1000}`,
      trainingId,
      trainingTitle: training?.title || "",
      trainingPrice: Math.floor(Math.random() * 2000) + 500,
      status,
      paymentStatus,
      enrollDate: enrollDate.format('YYYY-MM-DD'),
      approveDate: status !== "pending" ? enrollDate.add(Math.floor(Math.random() * 7), 'day').format('YYYY-MM-DD') : null,
      approver: status !== "pending" ? "管理员" + Math.floor(Math.random() * 5 + 1) : null,
      remark: `报名备注信息${i}`,
      rejectReason: status === "rejected" ? "不符合报名条件" : null,
      operationRecords: [
        {
          id: 1,
          type: "enroll",
          title: "学员报名",
          content: "学员提交报名申请",
          operator: "系统",
          createTime: enrollDate.format('YYYY-MM-DD HH:mm:ss')
        },
        ...(status !== "pending" ? [{
          id: 2,
          type: status === "approved" ? "approve" : "reject",
          title: status === "approved" ? "审核通过" : "审核拒绝",
          content: status === "approved" ? "报名审核通过" : "报名审核被拒绝",
          operator: "管理员" + Math.floor(Math.random() * 5 + 1),
          createTime: enrollDate.add(Math.floor(Math.random() * 7), 'day').format('YYYY-MM-DD HH:mm:ss')
        }] : []),
        ...(paymentStatus === "paid" ? [{
          id: 3,
          type: "payment",
          title: "支付成功",
          content: "学员完成课程费用支付",
          operator: "系统",
          createTime: enrollDate.add(Math.floor(Math.random() * 14), 'day').format('YYYY-MM-DD HH:mm:ss')
        }] : [])
      ]
    });
  }
  return mockData;
};

// 搜索
const handleSearch = () => {
  loadEnrollmentList();
};

// 重置
const handleReset = () => {
  filterForm.value = {
    enrollmentNo: "",
    studentName: "",
    trainingId: "",
    status: "",
    enrollDateRange: []
  };
  loadEnrollmentList();
};

// 导出
const handleExport = () => {
  ElMessage.success("导出功能开发中...");
};

// 查看报名详情
const handleView = (row: any) => {
  currentEnrollment.value = row;
  detailDialogVisible.value = true;
};

// 通过审核
const handleApprove = (row: any) => {
  currentEnrollment.value = row;
  approveType.value = "approve";
  approveForm.value = {
    rejectReason: "",
    remark: ""
  };
  approveDialogVisible.value = true;
};

// 拒绝审核
const handleReject = (row: any) => {
  currentEnrollment.value = row;
  approveType.value = "reject";
  approveForm.value = {
    rejectReason: "",
    remark: ""
  };
  approveDialogVisible.value = true;
};

// 提交审核
const handleApproveSubmit = async () => {
  try {
    if (approveType.value === "reject") {
      await approveFormRef.value.validate();
    }
    
    approveLoading.value = true;
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const action = approveType.value === "approve" ? "通过" : "拒绝";
    ElMessage.success(`审核${action}成功`);
    
    approveDialogVisible.value = false;
    detailDialogVisible.value = false;
    loadEnrollmentList();
  } catch (error) {
    console.error("审核失败", error);
  } finally {
    approveLoading.value = false;
  }
};

// 批量通过
const handleBatchApprove = async () => {
  try {
    await ElMessageBox.confirm(
      `确认通过选中的 ${selectedRows.value.length} 条报名申请吗？`,
      "批量通过",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    
    ElMessage.success(`已批量通过 ${selectedRows.value.length} 条报名申请`);
    loadEnrollmentList();
  } catch (error) {
    // 用户取消
  }
};

// 批量拒绝
const handleBatchReject = async () => {
  try {
    await ElMessageBox.confirm(
      `确认拒绝选中的 ${selectedRows.value.length} 条报名申请吗？`,
      "批量拒绝",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    
    ElMessage.success(`已批量拒绝 ${selectedRows.value.length} 条报名申请`);
    loadEnrollmentList();
  } catch (error) {
    // 用户取消
  }
};

// 催缴提醒
const handlePaymentReminder = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认向学员${row.studentName}发送缴费提醒吗？`,
      "催缴提醒",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }
    );
    
    ElMessage.success(`已向学员${row.studentName}发送缴费提醒`);
  } catch (error) {
    // 用户取消
  }
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection.filter(row => row.status === "pending");
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  loadEnrollmentList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadEnrollmentList();
};

// 加载报名列表
const loadEnrollmentList = async () => {
  try {
    loading.value = true;
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const mockData = generateMockData();
    enrollmentList.value = mockData.slice(
      (pagination.currentPage - 1) * pagination.pageSize,
      pagination.currentPage * pagination.pageSize
    );
    pagination.total = mockData.length;
  } catch (error) {
    ElMessage.error("加载报名列表失败");
  } finally {
    loading.value = false;
  }
};

// 组件挂载
onMounted(() => {
  loadEnrollmentList();
});
</script>

<style lang="scss" scoped>
.main {
  padding: 20px;
}

.filter-card {
  margin-bottom: 16px;
}

.stat-card {
  margin-bottom: 16px;
  
  .stat-content {
    display: flex;
    align-items: center;
    
    .stat-icon {
      width: 50px;
      height: 50px;
      border-radius: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      font-size: 20px;
      color: white;
      
      &.total-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      }
      
      &.pending-icon {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
      }
      
      &.approved-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.rate-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }
    
    .stat-info {
      flex: 1;
      
      .stat-title {
        font-size: 14px;
        color: #909399;
        margin-bottom: 8px;
      }
      
      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #303133;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.enrollment-detail {
  h4 {
    margin: 20px 0 10px 0;
    color: #303133;
    font-weight: bold;
  }
}

@media (max-width: 768px) {
  .main {
    padding: 10px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    
    .stat-icon {
      margin-right: 0;
      margin-bottom: 12px;
    }
  }
  
  .pagination-container {
    text-align: center;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: stretch;
  }
}
</style>